<?php

namespace modules\kefu;

use Throwable;
use think\facade\Db;
use Workerman\Lib\Timer;
use app\common\model\Config;
use app\common\library\Menu;
use GatewayWorker\Lib\Gateway;
use app\worker\library\kefu\Common;

class Kefu
{
    /**
     * 安装
     * @throws Throwable
     */
    public function install(): void
    {
        $this->createBackendMenu();
    }

    /**
     * 卸载
     * @throws Throwable
     */
    public function uninstall(): void
    {
        Menu::delete('kefu', true);
    }

    /**
     * 启用
     * @throws Throwable
     */
    public function enable(): void
    {
        Menu::enable('kefu');

        Config::addQuickEntrance('客服系统配置', 'kefu/config');
    }

    /**
     * 禁用
     * @throws Throwable
     */
    public function disable(): void
    {
        Menu::disable('kefu');

        Config::removeQuickEntrance('客服系统配置');
    }

    /**
     * 创建后台菜单
     * @throws Throwable
     */
    public function createBackendMenu(): void
    {
        $menu = [
            [
                'type'      => 'menu_dir',
                'title'     => '客服系统',
                'name'      => 'kefu',
                'path'      => 'kefu',
                'icon'      => 'fa fa-twitch',
                'pid'       => 0,
                'keepalive' => '1',
                'children'  => [
                    [
                        'type'      => 'menu',
                        'title'     => '客服配置',
                        'name'      => 'kefu/config',
                        'path'      => 'kefu/config',
                        'icon'      => 'fa fa-square-o',
                        'menu_type' => 'tab',
                        'component' => '/src/views/backend/kefu/config/index.vue',
                        'keepalive' => '1',
                        'weigh'     => 99,
                        'children'  => [
                            ['type' => 'button', 'title' => '查看', 'name' => 'kefu/config/index'],
                            ['type' => 'button', 'title' => '保存', 'name' => 'kefu/config/save'],
                        ],
                    ],
                    [
                        'type'      => 'menu',
                        'title'     => '用户管理',
                        'name'      => 'kefu/user',
                        'path'      => 'kefu/user',
                        'icon'      => 'fa fa-square-o',
                        'menu_type' => 'tab',
                        'component' => '/src/views/backend/kefu/user/index.vue',
                        'keepalive' => '1',
                        'weigh'     => 98,
                        'children'  => [
                            ['type' => 'button', 'title' => '查看', 'name' => 'kefu/user/index'],
                            ['type' => 'button', 'title' => '添加', 'name' => 'kefu/user/add'],
                            ['type' => 'button', 'title' => '编辑', 'name' => 'kefu/user/edit'],
                            ['type' => 'button', 'title' => '删除', 'name' => 'kefu/user/del'],
                        ],
                    ],
                    [
                        'type'      => 'menu',
                        'title'     => '会话管理',
                        'name'      => 'kefu/session',
                        'path'      => 'kefu/session',
                        'icon'      => 'fa fa-square-o',
                        'menu_type' => 'tab',
                        'component' => '/src/views/backend/kefu/session/index.vue',
                        'keepalive' => '1',
                        'weigh'     => 97,
                        'children'  => [
                            ['type' => 'button', 'title' => '查看', 'name' => 'kefu/session/index'],
                            ['type' => 'button', 'title' => '聊天记录', 'name' => 'kefu/session/records'],
                            ['type' => 'button', 'title' => '删除会话', 'name' => 'kefu/session/del'],
                        ],
                    ],
                    [
                        'type'      => 'menu',
                        'title'     => '分组管理',
                        'name'      => 'kefu/group',
                        'path'      => 'kefu/group',
                        'icon'      => 'fa fa-square-o',
                        'menu_type' => 'tab',
                        'component' => '/src/views/backend/kefu/group/index.vue',
                        'keepalive' => '1',
                        'weigh'     => 96,
                        'children'  => [
                            ['type' => 'button', 'title' => '查看', 'name' => 'kefu/group/index'],
                            ['type' => 'button', 'title' => '添加', 'name' => 'kefu/group/add'],
                            ['type' => 'button', 'title' => '编辑', 'name' => 'kefu/group/edit'],
                            ['type' => 'button', 'title' => '删除', 'name' => 'kefu/group/del'],
                            ['type' => 'button', 'title' => '快速排序', 'name' => 'kefu/group/sortable'],
                        ],
                    ],
                    [
                        'type'      => 'menu',
                        'title'     => '知识库管理',
                        'name'      => 'kefu/kbs',
                        'path'      => 'kefu/kbs',
                        'icon'      => 'fa fa-square-o',
                        'menu_type' => 'tab',
                        'component' => '/src/views/backend/kefu/kbs/index.vue',
                        'keepalive' => '1',
                        'weigh'     => 95,
                        'children'  => [
                            ['type' => 'button', 'title' => '查看', 'name' => 'kefu/kbs/index'],
                            ['type' => 'button', 'title' => '添加', 'name' => 'kefu/kbs/add'],
                            ['type' => 'button', 'title' => '编辑', 'name' => 'kefu/kbs/edit'],
                            ['type' => 'button', 'title' => '删除', 'name' => 'kefu/kbs/del'],
                            ['type' => 'button', 'title' => '快速排序', 'name' => 'kefu/kbs/sortable'],
                            ['type' => 'button', 'title' => '匹配度测试', 'name' => 'kefu/kbs/match'],
                        ],
                    ],
                    [
                        'type'      => 'menu',
                        'title'     => '快捷回复管理',
                        'name'      => 'kefu/quickReply',
                        'path'      => 'kefu/quickReply',
                        'icon'      => 'fa fa-square-o',
                        'menu_type' => 'tab',
                        'component' => '/src/views/backend/kefu/quickReply/index.vue',
                        'keepalive' => '1',
                        'weigh'     => 94,
                        'children'  => [
                            ['type' => 'button', 'title' => '查看', 'name' => 'kefu/quickReply/index'],
                            ['type' => 'button', 'title' => '添加', 'name' => 'kefu/quickReply/add'],
                            ['type' => 'button', 'title' => '编辑', 'name' => 'kefu/quickReply/edit'],
                            ['type' => 'button', 'title' => '删除', 'name' => 'kefu/quickReply/del'],
                            ['type' => 'button', 'title' => '快速排序', 'name' => 'kefu/quickReply/sortable'],
                        ],
                    ],
                    [
                        'type'      => 'menu',
                        'title'     => '用户轨迹管理',
                        'name'      => 'kefu/trajectory',
                        'path'      => 'kefu/trajectory',
                        'icon'      => 'fa fa-square-o',
                        'menu_type' => 'tab',
                        'component' => '/src/views/backend/kefu/trajectory/index.vue',
                        'keepalive' => '1',
                        'weigh'     => 93,
                        'children'  => [
                            ['type' => 'button', 'title' => '查看', 'name' => 'kefu/trajectory/index'],
                            ['type' => 'button', 'title' => '添加', 'name' => 'kefu/trajectory/add'],
                            ['type' => 'button', 'title' => '编辑', 'name' => 'kefu/trajectory/edit'],
                            ['type' => 'button', 'title' => '删除', 'name' => 'kefu/trajectory/del'],
                        ],
                    ],
                    [
                        'type'      => 'menu',
                        'title'     => '消息汇总记录管理',
                        'name'      => 'kefu/message',
                        'path'      => 'kefu/message',
                        'icon'      => 'fa fa-square-o',
                        'menu_type' => 'tab',
                        'component' => '/src/views/backend/kefu/message/index.vue',
                        'keepalive' => '1',
                        'weigh'     => 92,
                        'children'  => [
                            ['type' => 'button', 'title' => '查看', 'name' => 'kefu/message/index'],
                            ['type' => 'button', 'title' => '添加', 'name' => 'kefu/message/add'],
                            ['type' => 'button', 'title' => '编辑', 'name' => 'kefu/message/edit'],
                            ['type' => 'button', 'title' => '删除', 'name' => 'kefu/message/del'],
                        ],
                    ],
                ],
            ]
        ];
        Menu::create($menu);
    }

    /**
     * Workerman 进程启动时
     * @throws Throwable
     */
    public function onWorkerStart($arg): void
    {
        // 第一个进程启动
        if ($arg['worker']->id == 0) {
            // 重置客服接待信息
            Db::name('kefu_reception_log')
                ->where('status', 0)
                ->update([
                    'status' => 1,
                ]);
            Db::name('kefu_user')
                ->where('identity', 'csr')
                ->where('csr_reception_count', '<>', 0)
                ->update([
                    'csr_reception_count' => 0,
                ]);

            // 重置用户状态
            Db::name('kefu_user')
                ->where('status', '<>', 'offline')
                ->update([
                    'status' => 'offline'
                ]);
        }
    }

    /**
     * 向 Workerman 模块注册连接断开时的方法
     * @throws Throwable
     */
    public function onWebSocketClose(): void
    {
        $newStatus = Common::changeUserStatus('offline');

        if ($newStatus == 'offline') {
            $user = Common::getUser();
            $json = json_encode([
                'type' => 'changeStatus',
                'data' => ['status' => $newStatus] + $user,
                'time' => time(),
            ]);
            if ($user['identity'] == 'csr') {
                // 发送给所有人
                Gateway::sendToAll($json);
            } else {
                // 客服代表的接待量修改
                Timer::add(600, function () use ($user) {
                    $receptionLogs = Db::name('kefu_reception_log')
                        ->where('user_id', $user['id'])
                        ->where('status', 0)
                        ->select();
                    foreach ($receptionLogs as $receptionLog) {
                        if (!Gateway::isUidOnline(Common::mark('uid', $user))) {
                            Common::csrReceptionHandle($receptionLog['csr_id'], $user['id'], 'dec');
                        }
                    }
                }, [], false);

                // 发送给客服代表
                Gateway::sendToGroup(Common::mark('csrGroup'), $json);
            }
        }
    }
}